package com.example.springbooteasycode.zjrc.project.Koal;

import java.util.Arrays;

public class ByteConversionExample {
    public static void main(String[] args) {
        // 1. 原始 byte[]
        byte[] originalBytes = {0, 77, 106, -74};
        System.out.println("原始 byte[]: " + Arrays.toString(originalBytes));

        // 2. 转换为无符号 int[]
        int[] unsignedArray = toUnsignedArray(originalBytes);
        System.out.println("转换为无符号 int[]: " + Arrays.toString(unsignedArray));

        // 3. 转回 byte[]
        byte[] restoredBytes = toByteArray(unsignedArray);
        System.out.println("转回 byte[]: " + Arrays.toString(restoredBytes));

        // 验证是否与原始数组相同
        System.out.println("是否与原始数组相同: " + Arrays.equals(originalBytes, restoredBytes));
    }

    // byte[] 转无符号 int[]
    public static int[] toUnsignedArray(byte[] bytes) {
        int[] result = new int[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            result[i] = bytes[i] & 0xFF;
        }
        return result;
    }

    // 无符号 int[] 转 byte[]
    public static byte[] toByteArray(int[] unsignedArray) {
        byte[] result = new byte[unsignedArray.length];
        for (int i = 0; i < unsignedArray.length; i++) {
            // 确保数值在 byte 范围内（0-255）
            if (unsignedArray[i] < 0 || unsignedArray[i] > 255) {
                throw new IllegalArgumentException("数值超出无符号字节范围: " + unsignedArray[i]);
            }
            result[i] = (byte) unsignedArray[i];
        }
        return result;
    }
}
